﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;

namespace TireService.Website.Kunde
{
    public partial class Rabat : System.Web.UI.Page
    {
        #region Public Properties

        public int CustomerId
        {
            get
            {
                if (ViewState["_customerid"] != null)
                    return (int)ViewState["_customerid"];
                else
                    return (int)Session["CustomerId"];
            }
            set
            {
                ViewState["_customerid"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

            }

            BindCustomerQuotation(db, this.CustomerId);
        }

        /// <summary>
        /// Function that bind customer quotations to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindCustomerQuotation(TireServiceDB db, int CustomerId)
        {
            // Bind to gridview
            gvQuotation.DataSource = db.GetCustomerQuotation(CustomerId);
            gvQuotation.DataBind();
        }

        /// <summary>
        /// Callback function that send email with voucher
        /// </summary>
        protected void callbackSendQuotation_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values (0: Email, 1: Subscription, 2: Message)
                string[] param = e.Parameter.Split('|');

                // Initiate database connection
                TireServiceDB db = new TireServiceDB();

                Customer customer = db.GetCustomer(this.CustomerId);

                // Create quotation
                Quotation quotation = new Quotation();

                quotation.QuotationId = db.Quotations.Max(p => p.QuotationId) + 1;
                quotation.ReferenceCustomerId = this.CustomerId;
                quotation.SendOutEmail = param[0];
                quotation.QuotationTypeId = 1;
                quotation.ActivationLimit = 1;
                quotation.OneTimeDiscount = true;

                db.AddQuotation(quotation);

                QuotationDetail quotationdetail = new QuotationDetail();

                quotation.QuotationDetails.Add(quotationdetail);

                Subscription subscription = db.GetSubscription(Convert.ToInt16(param[1]));

                quotationdetail.ProductNumber = subscription.EconomicProductNumber;
                quotationdetail.SubscriptionId = subscription.SubscriptionId;
                quotationdetail.Description = subscription.Description + " - 10% rabat";
                quotationdetail.Quantity = 1;
                quotationdetail.UnitPrice = subscription.StandardPrice - (subscription.StandardPrice* Convert.ToDecimal(0.1));

                db.SubmitChanges();

                // Create voucher
                string voucher = quotation.QuotationId.ToString() + "-" + quotation.Createdate.Year.ToString() + "-" + quotation.QuotationCode.ToString();

                // Prepare email
                EmailNotificationServices emailService = new EmailNotificationServices();

                string CustomerMessage = "";

                if (param[2] != null & param[2] != string.Empty)
	            {
		            CustomerMessage = param[2] + "<br><br>";
	            }

                // Send email to receiver
                emailService.Customer_Voucher_SendEmail(param[0], customer.Name, CustomerMessage, voucher);

                ////// Return values to client
                //e.Result = "Email blev sendt til " + param[0] + " med beskeden: " + param[1];
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        #region GridView Functions

        /// <summary>
        /// Postback function that updates quotation gridview list
        /// </summary>
        protected void gvQuotation_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            BindCustomerQuotation(db, this.CustomerId);
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvQuotation_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn FullQuotationCode: Show voucher code
            if (e.Column.FieldName == "FullQuotationCode")
            {
                // Get QuotationId
                int QuotationId = Convert.ToInt32(e.GetListSourceFieldValue("QuotationId"));
                int QuotationCode = Convert.ToInt32(e.GetListSourceFieldValue("QuotationCode"));
                DateTime Createdate = Convert.ToDateTime(e.GetListSourceFieldValue("Createdate"));

                // Change field value
                e.Value = QuotationId.ToString() + "-" + Createdate.Year.ToString() + "-" + QuotationCode.ToString();
            }
        }

        #endregion
    }
}